package com.chukun.gateway.core.filter.impl;

import com.chukun.gateway.common.rule.Rule;
import com.chukun.gateway.core.context.GatewayContext;
import com.chukun.gateway.core.filter.Filter;
import com.chukun.gateway.core.filter.annotation.FilterDefinition;
import com.chukun.gateway.core.limiter.rule.IGatewayFlowCtlRule;
import com.chukun.gateway.core.limiter.rule.impl.FlowControlByPathRule;
import lombok.extern.slf4j.Slf4j;

import java.util.Iterator;
import java.util.Set;

import static com.chukun.gateway.common.constants.GlobalFilterConst.*;

/**
 * @author chukun
 * @version 1.0.0
 * @description 限流的过滤器
 * @createTime 2023/12/10 20:52
 */
@Slf4j
@FilterDefinition(id=FLOW_CTL_FILTER_ID, name = FLOW_CTL_FILTER_NAME, order = FLOW_CTL_FILTER_ORDER)
public class FlowLimiterFilter implements Filter {


    @Override
    public void doFilter(GatewayContext ctx) throws Exception {
        Rule rule = ctx.getRule();
        if(rule == null) {
            return;
        }
        Set<Rule.FlowControlConfig> flowCtlConfigs = rule.getFlowCtlConfigs();
        Iterator<Rule.FlowControlConfig> iterator = flowCtlConfigs.iterator();
        Rule.FlowControlConfig flowCtlConfig;
        IGatewayFlowCtlRule flowCtlRule = null;
        while (iterator.hasNext()){
            flowCtlConfig = iterator.next();
            if(flowCtlConfig == null){
                continue;
            }
            String path = ctx.getRequest().getPath();
            if(flowCtlConfig.getType().equalsIgnoreCase(FLOW_CTL_TYPE_PATH) && path.equals(flowCtlConfig.getValue())){
                flowCtlRule = FlowControlByPathRule.getInstance(rule.getServiceId(), path);
            }else if(flowCtlConfig.getType().equalsIgnoreCase(FLOW_CTL_TYPE_SERVICE)){

            }
            if(flowCtlRule != null){
                flowCtlRule.doFlowControlFilter(flowCtlConfig,rule.getServiceId());
            }
        }
    }
}
